package com.example.homework.adapter;


import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.homework.R;
import com.example.homework.bean.VideoItem;

import java.util.List;

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {
    public List<VideoItem> videoItems;

    public VideoAdapter(List<VideoItem> videoItems) {this.videoItems = videoItems;}

    @Override
    public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new VideoViewHolder(LayoutInflater.from(parent.getContext())
        .inflate(R.layout.video_item,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
        holder.setData(videoItems.get(position));
    }

    @Override
    public int getItemCount() {
        return videoItems.size();
    }

    static class VideoViewHolder extends RecyclerView.ViewHolder{
        VideoView videoView;
        TextView videoTitle,videoSubTitle;
        ProgressBar progressBar;


        public VideoViewHolder(View itemView) {
            super(itemView);
            videoView = itemView.findViewById(R.id.videoView);
            videoTitle = itemView.findViewById(R.id.textViewTitle);
            videoSubTitle = itemView.findViewById(R.id.textViewSubTitle);
            progressBar = itemView.findViewById(R.id.progressBar);
        }


        public void setData(VideoItem videoItem) {
            videoTitle.setText(videoItem.videoTitle);
            videoSubTitle.setText(videoItem.videoSubTitle);
            videoView.setVideoPath(videoItem.videoURL);
            videoView.setOnPreparedListener(mediaPlayer -> {
                progressBar.setVisibility(View.GONE);
                mediaPlayer.start();
            });
            videoView.setOnCompletionListener(MediaPlayer::start);
        }
    }
}
